<?php

namespace app\api\controller\v2;

use app\admin\model\ConfigValueModel;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\Collection;
use app\common\model\Publish as ThisModel;
use app\common\model\PublishComment;
use app\common\model\User;
use think\Db;
use think\Exception;

/**
 * 会员接口
 */
class Publish extends Api
{
    protected $noNeedLogin = ['getType','allLists'];
    protected $noNeedRight = '*';

    /**
     * @brief   发布转租
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function sublease()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id=$user->id;
        $keys=$this->get_keys('sublease'.$user_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Publish();
        $check_result=$validate->scene('sublease')->check($getData);
        $user_info=User::where(['id'=>$user_id])->find();
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        if($user_info['is_forbid']==1){
            $this->del_rekey($keys);
            $this->error('禁止发帖');
        }
        // 检测是否可发布
        $publish_type = User::isCanPublish($user_id);
        if ($publish_type == 0) {
            $this->del_rekey($keys);
            $this->error('次数已用完，积分不足');
        }


        $phone = $getData['phone'];
        if ($phone && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->del_rekey($keys);
            $this->error('手机号格式错误');
        }
        if (!empty($getData['end_time'])) {
            if(date('Y-m-d',strtotime($getData['end_time']))!=$getData['end_time']){
                $this->del_rekey($keys);
                $this->error('到期时间格式错误');
            }
        }
        if (!empty($getData['lng'])) {
            $check_result=$validate->scene('sublease_lng')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['lat'])) {
            $check_result=$validate->scene('sublease_lat')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['tags'])) {
            $check_result=$validate->scene('sublease_tags')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['address'])) {
            $check_result=$validate->scene('sublease_address')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }

        if (!empty($getData['desc'])) {
            $check_result=$validate->scene('sublease_desc')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['photos'])) {
            $photos=explode(',',$getData['photos']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg','mp4','avi','mkv','wmv','flv','mov','3gp','rmvb'])){
                    $this->del_rekey($keys);
                    $this->error('文件格式错误');
                }
            }
        }
        $is_audit = User::where('id', $user_id)->value('is_audit');
        $insert_data=[
            'user_id'=>$user_id,
            'area_id'=>$getData['area_id'],
            'money'=>$getData['money'],
            'house_type'=>$getData['house_type'],
            'contract_type'=>$getData['contract_type'],
            'type'=>$getData['type'],
            'floor'=>$getData['floor'] ?? 0,
            'name'=>$getData['name'],
            //'phone'=>$getData['phone'],
            'wx_num'=>$getData['wx_num'],
            'lng'=>$getData['lng'],
            'photos'=>$getData['photos'],
            'lat'=>$getData['lat'],
            'tags'=>$getData['tags'],
            'address'=>$getData['address'],
            'send_type'=>1,
            'status'=>$is_audit == 0 ? '1' : '0',
            'desc'=>$getData['desc'],
        ];
        //php71 think crud -t user_publish --relation=user --relation=area --relationforeignkey=user_id --relationforeignkey=area_id --imagefield=photos
        //php71 think crud -t user_publish -d 1
        //检测重复
        if (ThisModel::where($insert_data)->find()) {
            $this->del_rekey($keys);
            $this->error('重复提交');
        }
        Db::startTrans();
        try {
            ThisModel::create($insert_data);
            User::decPublishNum($user_id, $publish_type);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } finally {
            $this->del_rekey($keys);
        }
        $this->success('提交成功');
    }

    /**
     * @brief   发布便民广告
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function advice()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id=$user->id;
        $keys=$this->get_keys('advice'.$user_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Publish();
        $check_result=$validate->scene('advice')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        $user_info=User::where(['id'=>$user_id])->find();
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }

        if($user_info['is_forbid']==1){
            $this->del_rekey($keys);
            $this->error('禁止发帖');
        }
        // 检测是否可发布
        $publish_type = User::isCanPublish($user_id);
        if ($publish_type == 0) {
            $this->del_rekey($keys);
            $this->success('积分不足',['is_recharge' => 1]);
        }
        $phone = $getData['phone'];
        if ($phone && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->del_rekey($keys);
            $this->error('手机号格式错误');
        }
        if (!empty($getData['lng'])) {
            $check_result=$validate->scene('sublease_lng')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['lat'])) {
            $check_result=$validate->scene('sublease_lat')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['tags'])) {
            $check_result=$validate->scene('sublease_tags')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['address'])) {
            $check_result=$validate->scene('sublease_address')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['desc'])) {
            $check_result=$validate->scene('sublease_desc')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['attachment'])) {
            $check_result=$validate->scene('sublease_attachment')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
            $ext_arr=explode('.',$getData['attachment']);
            if(!in_array($ext_arr[count($ext_arr)-1],['zip','rar'])){
                $this->del_rekey($keys);
                $this->error('附件格式错误');
            }
        }
        if (!empty($getData['photos'])) {
            $photos=explode(',',$getData['photos']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg','mp4','avi','mkv','wmv','flv','mov','3gp','rmvb'])){
                    $this->del_rekey($keys);
                    $this->error('文件格式错误');
                }
            }
        }
        $is_audit = User::where('id',$user_id)->value('is_audit');
        $insert_data = [
            'user_id' => $user_id,
            'area_id' => $getData['area_id'],
//            'money'=>$getData['money'],
            'name' => $getData['name'],
//            'phone' => $getData['phone'],
            'wx_num' => $getData['wx_num'],
            'lng' => $getData['lng'],
            'photos' => $getData['photos'],
            'lat' => $getData['lat'],
            'tags' => $getData['tags'],
            'address' => $getData['address'],
            'send_type' => 2,
            'status' => $is_audit == 0 ? '1' : '0',
            'desc' => $getData['desc'],
            'attachment' => $getData['attachment'],
        ];
        //php71 think crud -t user_publish --relation=user --relation=area --relationforeignkey=user_id --relationforeignkey=area_id --imagefield=photos
        //php71 think crud -t user_publish -d 1
        //检测重复
        if(ThisModel::where($insert_data)->find()){
            $this->del_rekey($keys);
            $this->error('重复提交');
        }

        // 置顶处理
        if (!empty($getData['is_top'])) {
            $top_config = ThisModel::getTopConfig();
            $top_config = array_column($top_config, null, 'day');
            $top_day = $getData['top_day'] ?? 0;
            if (!$top_day || !array_key_exists($top_day, $top_config)) {
                $this->error('置顶天数错误');
            }

            $insert_data['is_top'] = 1;
            $insert_data['top_day'] = $top_day;
            $insert_data['top_end_time'] = strtotime("+$top_day day");

            $top_score = $top_config[$top_day]['score'] ?? 0;
            if ($this->auth->score < $top_score + intval(config('site.publish_score'))) {
                $this->success('积分不足，请先充值', ['is_recharge' => 1]);
            }
        }

        Db::startTrans();
        try {

            User::decPublishNum($user_id, $publish_type);
            // 置顶处理
            if (!empty($getData['is_top'])) {
                User::score(-1 * $top_score, $user_id, '便民广告置顶扣除', 8);
            }

            ThisModel::create($insert_data, true);


            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } finally {
            $this->del_rekey($keys);
        }
        $this->success('提交成功', ['is_recharge' => 0]);
    }
    /**
     * @brief   发布附近商圈
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function shop()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id=$user->id;
        $keys=$this->get_keys('shop'.$user_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Publish();
        $check_result=$validate->scene('advice')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        $user_info=User::where(['id'=>$user_id])->find();
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }

        if($user_info['is_forbid']==1){
            $this->del_rekey($keys);
            $this->error('禁止发帖');
        }
        // 检测是否可发布
        $publish_type = User::isCanPublish($user_id);
        if ($publish_type == 0) {
            $this->del_rekey($keys);
            $this->error('积分不足');
        }
        $phone = $getData['phone'];
        if ($phone && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->del_rekey($keys);
            $this->error('手机号格式错误');
        }
        if (!empty($getData['lng'])) {
            $check_result=$validate->scene('sublease_lng')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['lat'])) {
            $check_result=$validate->scene('sublease_lat')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['tags'])) {
            $check_result=$validate->scene('sublease_tags')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['address'])) {
            $check_result=$validate->scene('sublease_address')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['desc'])) {
            $check_result=$validate->scene('sublease_desc')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
        }
        if (!empty($getData['attachment'])) {
            $check_result=$validate->scene('sublease_attachment')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
            $ext_arr=explode('.',$getData['attachment']);
            if(!in_array($ext_arr[count($ext_arr)-1],['zip','rar'])){
                $this->del_rekey($keys);
                $this->error('附件格式错误');
            }
        }
        if (!empty($getData['photos'])) {
            $photos=explode(',',$getData['photos']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg','mp4','avi','mkv','wmv','flv','mov','3gp','rmvb'])){
                    $this->del_rekey($keys);
                    $this->error('文件格式错误');
                }
            }
        }
        $is_audit = User::where('id',$user_id)->value('is_audit');
        $insert_data=[
            'user_id'=>$user_id,
            'area_id'=>$getData['area_id'],
//            'money'=>$getData['money'],
            'name'=>$getData['name'],
            //'phone'=>$getData['phone'],
            'wx_num'=>$getData['wx_num'],
            'lng'=>$getData['lng'],
            'photos'=>$getData['photos'],
            'lat'=>$getData['lat'],
            'tags'=>$getData['tags'],
            'address'=>$getData['address'],
            'send_type'=>3,
            'status'=>$is_audit == 0 ? '1' : '0',
            'desc'=>$getData['desc'],
            'attachment'=>$getData['attachment'],
        ];
        //php71 think crud -t user_publish --relation=user --relation=area --relationforeignkey=user_id --relationforeignkey=area_id --imagefield=photos
        //php71 think crud -t user_publish -d 1
        //检测重复

        if(ThisModel::where($insert_data)->find()){
            $this->del_rekey($keys);
            $this->error('重复提交');
        }

        Db::startTrans();
        try {
            ThisModel::create($insert_data);
            User::decPublishNum($user_id, $publish_type);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } finally {
            $this->del_rekey($keys);
        }
        $this->success('提交成功');
    }

    /**
     * @brief   获取发送限制
     * @author wanchengniuniu
     * @date 2025/4/9
     *
     * @param
     * @return
     */
    public function getSendType()
    {
        //$send_hose_mode=config('site.send_hose_mode');
        $send_hose_mode=1;
        $text='免费发布';
        $status=false;
        if(in_array($send_hose_mode,[2,3])){
            $status=true;
            if($send_hose_mode==2){
                $text='仅会员可发布';
            }
            if($send_hose_mode==3){
                //限制积分
                $text='积分达到'.config('site.publish_score_limit').'可发布';

            }
        }
        $re_data=[
            'status'=>$status,
            'text'=>$text,
        ];
        $this->success('获取成功',$re_data);
    }

    /**
     * @brief   获取转租类型
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function getType()
    {
        $list=ThisModel::getTranTypeList();
        $this->success('获取成功',$list);
    }
    /**
     * @brief   获取转租户型
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function getHouseType()
    {
        $list=ThisModel::getHouseTypeList();
        $this->success('获取成功',$list);
    }
    /**
     * @brief   获取转租合同方式
     * @author wanchengniuniu
     * @date 2025/2/26
     */
    public function getContractType()
    {
        $list=ThisModel::getContractTypeList();
        $this->success('获取成功',$list);
    }

    /**
     * 获取我的发布列表
     */

    public function lists(){
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $status = $this->request->post('status/s', '1');
            $user_id = $user->id;
            $limit = $this->request->param('limit/d', 10);

            $where = ['p.status' => $status, 'p.user_id' => $user_id];
            $Data = ThisModel::alias('p')
                ->join('fa_user u', 'u.id=p.user_id')
                ->field('p.*,u.nickname,u.avatar,u.loginip')
                ->where($where)
                ->order('p.id', 'desc')
                ->paginate($limit)
                ->each(function ($item){
                    $item['photos_path']=explode(',',$item['photos']);
                    $item['first_photos_path']= $item['photos_path'][0] ?? [];
                    $item['status_text']=ThisModel::getStatusList(1,$item['status']);
                    $item['updatetime']=date('Y-m-d H:i',$item['updatetime']);
                    $item['photos_path']=get_all_img_path($item['photos']);
                    $item['attachment_path']=get_all_img_path($item['attachment']);
                    $send_type_text='';
                    if(!empty($item['send_type'])){
                        $send_type_text=ThisModel::getSendTypeList(1,$item['send_type']);
                    }
                    $item['send_type_text']=$send_type_text;
                    $house_type_text='';
                    if(!empty($item['house_type'])){
                        $house_type_text=ThisModel::getHouseTypeList(1,$item['house_type']);
                    }
                    $item['house_type_text']=$house_type_text;
                    $contract_type_text='';
                    if(!empty($item['contract_type'])){
                        $contract_type_text=ThisModel::getContractTypeList(1,$item['contract_type']);
                    }
                    $item['contract_type_text']=$contract_type_text;
                    $type_text='';
                    if(!empty($item['type'])){
                        $type_text=ThisModel::getTranTypeList(1,$item['type']);
                    }
                    $item['type_text']=$type_text;

                    $item['zan_user'] = $this->getZanUserList($item['id']);
                    $item['comment_list'] = $this->getCommentList($item['id']);
                    return $item;
                });
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的发布详情
     */

    public function detail(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $id = $this->request->post('id/d', 0);
            $user_id=$user->id;
            $where = ['p.user_id'=>$user_id,'p.id'=>$id];
            $item = ThisModel::alias('p')
                ->join('fa_user u','u.id=p.user_id')
                ->field('p.*,u.nickname,u.avatar,u.loginip')
                ->where($where)->find();

            $item['photos_path']=get_all_img_path($item['photos']);
            $item['attachment_path']=get_all_img_path($item['attachment']);
            $item['first_photos_path']=isset($item['photos_path'][0])?$item['photos_path'][0]:[];
            $item['status_text']=ThisModel::getStatusList(1,$item['status']);
            $item['updatetime']=date('Y-m-d H:i',$item['updatetime']);

            $send_type_text='';
            if(!empty($item['send_type'])){
                $send_type_text=ThisModel::getSendTypeList(1,$item['send_type']);
            }
            $item['send_type_text']=$send_type_text;
            $house_type_text='';
            if(!empty($item['house_type'])){
                $house_type_text=ThisModel::getHouseTypeList(1,$item['house_type']);
            }
            $item['house_type_text']=$house_type_text;
            $contract_type_text='';
            if(!empty($item['contract_type'])){
                $contract_type_text=ThisModel::getContractTypeList(1,$item['contract_type']);
            }
            $item['contract_type_text']=$contract_type_text;
            $type_text='';
            if(!empty($item['type'])){
                $type_text=ThisModel::getTranTypeList(1,$item['type']);
            }
            $item['type_text']=$type_text;

            $item['zan_user'] = $this->getZanUserList($id);
            $item['cang_num']=Collection::where(['type'=>Collection::TYPE_CANG,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->count();
            $item['zan_num']=Collection::where(['type'=>Collection::TYPE_ZAN,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->count();
            $item['comment_list'] = $this->getCommentList($item['id']);

            $this->success('查询成功',$item);
        }else{
            $this->error('请求参数有误');
        }
    }


    public function del()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'id|ID' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        $row = ThisModel::get($params['id']);
        if (empty($row)) $this->error('数据不存在');
        if ($row['user_id'] != $this->auth->id) {
            $this->error('只能删除自己的');
        }

        if ($row->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 获取发布列表
     */

    public function allLists(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $auth = Auth::instance();
            $user_id = 0;
            if($auth->isLogin()){
                $user = $this->auth->getUser();
                $user_id = $user->id;
            }


            $limit = $this->request->param('limit/d', 10);
            $area_id = $this->request->param('area_id/d', 0);
            $order_by = $this->request->param('order/d', 0);
            $publisher = $this->request->param('publisher/d', 0);
            $user_lng = !empty($getData['lng']) ? $getData['lng'] : 0;
            $user_lat = !empty($getData['lat']) ? $getData['lat'] : 0;
            $km = !empty($getData['km']) ? $getData['km'] : 5000;
            $housetype = !empty($getData['housetype']) ? $getData['housetype'] : 0;
            $selectedTagsType = !empty($getData['selectedTagsType']) ? $getData['selectedTagsType'] : 0;

            $type = $getData['type'] ?? 0;//1显示0待审核3已过期
            $where1 = '';
            $where = ['p.send_type' => $type, 'p.status' => "1"];
            if($auth->isLogin()) {
                if ($publisher) {
                    $where['p.user_id'] = $publisher;
                }
            }
            if ($area_id) {
                $where['p.area_id'] = $area_id;
            }

            if ($housetype) {
                $where['p.type'] = $housetype;
            }
            if ($selectedTagsType) {
                $where1 .= 'p.house_type in (' . $selectedTagsType . ')';
            }
            $field = 'p.id,p.phone,p.attachment,p.updatetime,p.click,p.fen_num,p.area_id,p.money,p.house_type,p.contract_type,p.send_type,p.type,p.name,p.user_id,p.lng,p.photos,p.lat,p.tags,p.address,p.desc,p.floor,u.nickname,u.avatar,u.loginip';
            $order = '';
            if ($order_by) {
                if ($order_by == 1) {
                    $order = 'click desc';
                }
                if ($order_by == 2) {
                    $order = 'updatetime desc';
                }
                if ($order_by == 3) {
                    if (!empty($user_lng) && !empty($user_lat) && !empty($km)) {
                        $array = returnSquarePoint($user_lng, $user_lat, $km);
                        if (!empty($where1)) {
                            $where1 .= ' and p.lat > ' . $array['right-bottom']['lat'] . ' and ';
                        } else {
                            $where1 .= 'p.lat > ' . $array['right-bottom']['lat'] . ' and ';
                        }
                        $where1 .= 'p.lng > ' . $array['left-top']['lng'] . ' and ';
                        $where1 .= 'p.lat < ' . $array['left-top']['lat'] . ' and ';
                        $where1 .= 'p.lng < ' . $array['right-bottom']['lng'];
                        $order = "distance ASC"; // 按照距离升序排序
                    }
                }
            }
            if (!empty($user_lng) && !empty($user_lat) && !empty($km)) {
                $field .= ", 6371 * acos(
    cos(radians({$user_lat})) * cos(radians(p.lat)) * cos(radians(p.lng) - radians({$user_lng}))
    + sin(radians({$user_lat})) * sin(radians(p.lat))
) AS distance";
            }

            ThisModel::update(['is_top' => 0], [
                'is_top' => 1,
                'top_end_time' => ['<', time()],
            ]);

            $order = $order ? 'is_top desc,' . $order : 'is_top desc,id desc';
            $Data = ThisModel::alias('p')
                ->join('fa_user u', 'u.id=p.user_id')
                ->field($field)
                ->where($where)->where($where1)
                ->order($order)
                ->paginate($limit)
                ->each(function ($item) use ($user_id) {
                    $item['updatetime'] = date('Y-m-d H:i', $item['updatetime']);
                    $item['first_photos_path'] = $item['photos_path'][0] ?? [];
                    $item['photos_path'] = get_all_img_path($item['photos']);
                    $item['attachment_path'] = get_all_img_path($item['attachment']);
                    $house_type_text = '';
                    if (!empty($item['house_type'])) {
                        $house_type_text = ThisModel::getHouseTypeList(1, $item['house_type']);
                    }
                    $contract_type_text = '';
                    if (!empty($item['contract_type'])) {
                        $contract_type_text = ThisModel::getContractTypeList(1, $item['contract_type']);
                    }
                    $type_text = '';
                    if (!empty($item['type'])) {
                        $type_text = ThisModel::getTranTypeList(1, $item['type']);
                    }
                    $item['send_type_text'] = ThisModel::getSendTypeList(1, $item['send_type']);
                    $item['house_type'] = $house_type_text;
                    $item['contract_type'] = $contract_type_text;
                    $item['type_text'] = $type_text;
                    $area = '';
                    if (!empty($item['area_id'])) {
                        $area_info = ConfigValueModel::where(['option_id' => $item['area_id'], 'cid' => 2])->find();
                        $area = $area_info['option_name'] ?? '';
//                        if($area_info['pid']!=0){
//                            $area_pinfo=ConfigValueModel::where(['id'=>$area_info['pid']])->find();
//                            $area=$area_pinfo['option_name'].'-'.$area;
//                        }
                    }
                    $item['area_info'] = $area;
                    $item['zan'] = 0;
                    $item['cang'] = 0;
                    //检测是否有收藏
                    if($user_id){
                        $info = Collection::where(['user_id' => $user_id, 'type' => Collection::TYPE_ZAN, 'operate_type' => Collection::STATUS_NORMAL, 'product_id' => $item['id']])->find();
                        if ($info) {
                            $item['zan'] = 1;
                        }
                        $info = Collection::where(['user_id' => $user_id, 'type' => Collection::TYPE_CANG, 'operate_type' => Collection::STATUS_NORMAL, 'product_id' => $item['id']])->find();
                        if ($info) {
                            $item['cang'] = 1;
                        }
                    }
                    $item['zan_user'] = $this->getZanUserList($item['id']);

                    $item['comment_list'] = $this->getCommentList($item['id']);
                    return $item;
                });
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    private function getZanUserList($pub_id)
    {
        $user_ids = Collection::where([
            'type' => Collection::TYPE_ZAN,
            'operate_type' => Collection::STATUS_NORMAL,
            'product_id' => $pub_id
        ])->column('user_id');

        if (empty($user_ids)) {
            return [];
        }

        return User::whereIn('id', $user_ids)->field('id,nickname,avatar')->select();
    }

    private function getCommentList($pub_id, $pid = 0)
    {
        $list = PublishComment::alias('c')
            ->join('user u','c.user_id = u.id', 'left')
            ->field('c.id,c.user_id,u.username,c.content')
            ->where('c.pub_id', $pub_id)
            ->where('c.status', 1)
            ->where('c.pid', $pid)
            ->order('c.id','desc')
            ->select();

        foreach ($list as &$item) {
            $item['can_del'] = $item['user_id'] == $this->auth->id ? 1 : 0;
            $item['list'] = $this->getCommentList($pub_id, $item['id']);
        }
        unset($item);
        return $list;
    }

    /**
     * 获取发布详情
     */

    public function allDetail(){
        if($this->request->isPost()){
            $id = $this->request->post('id/d', 0);
            $user = $this->auth->getUser();
            $user_id=$user->id;

            $where = ['p.id'=>$id,'p.status'=> "1"];
            $item = ThisModel::alias('p')
                ->join('fa_user u','u.id=p.user_id')
                ->field('p.id,p.send_type,p.phone,p.area_id,p.attachment,p.money,p.house_type,p.updatetime,p.click,p.fen_num,p.contract_type,p.type,p.name,p.user_id,p.lng,p.photos,p.lat,p.tags,p.address,p.desc,p.floor,u.nickname,u.avatar,u.loginip')
                ->where($where)->find();
            if(!$item){
                $this->error('查询失败');
            }
            $item['photos_path']=get_all_img_path($item['photos']);
            $item['attachment_path']=get_all_img_path($item['attachment']);
            $item['first_photos_path']=isset($item['photos_path'][0])?$item['photos_path'][0]:[];
            $item['updatetime']=date('Y-m-d H:i',$item['updatetime']);
            $house_type_text='';
            if(!empty($item['house_type'])){
                $house_type_text=ThisModel::getHouseTypeList(1,$item['house_type']);
            }
            $contract_type_text='';
            if(!empty($item['contract_type'])){
                $contract_type_text=ThisModel::getContractTypeList(1,$item['contract_type']);
            }
            $type_text='';
            if(!empty($item['type'])){
                $type_text=ThisModel::getTranTypeList(1,$item['type']);
            }
            $item['send_type_text']=ThisModel::getSendTypeList(1,$item['send_type']);
            $item['house_type']=$house_type_text;
            $item['contract_type']=$contract_type_text;
            $item['type_text']=$type_text;
            $area='';
            if(!empty($item['area_id'])){
                $area_info=ConfigValueModel::where(['option_id'=>$item['area_id'],'cid'=>2])->find();
                $area=$area_info['option_name'];
//                if($area_info['pid']!=0){
//                    $area_pinfo=ConfigValueModel::where(['id'=>$area_info['pid']])->find();
//                    $area=$area_pinfo['option_name'].'-'.$area;
//                }
            }
            $item['area_info']=$area;
            ThisModel::where(['id'=>$id])->setInc('click',1);
            $item['zan']=0;
            $item['cang']=0;
            //检测是否有收藏
            $info=Collection::where(['user_id'=>$user_id,'type'=>Collection::TYPE_ZAN,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->find();
            if($info){
                $item['zan']=1;
            }
            $item['zan_user'] = $this->getZanUserList($id);
            $info=Collection::where(['user_id'=>$user_id,'type'=>Collection::TYPE_CANG,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->find();
            if($info){
                $item['cang']=1;
            }
            $item['cang_num']=Collection::where(['type'=>Collection::TYPE_CANG,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->count();
            $item['zan_num']=Collection::where(['type'=>Collection::TYPE_ZAN,'operate_type'=>Collection::STATUS_NORMAL,'product_id'=>$item['id']])->count();
            $item['comment_list'] = $this->getCommentList($item['id']);

            $this->success('查询成功',$item);

        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 发布分享
     */

    public function allDetailFen(){
        if($this->request->isPost()){
            $id = $this->request->post('id/d', 0);
            $where = ['p.id'=>$id,'p.status'=> "1"];
            $item = ThisModel::alias('p')
                ->join('fa_user u','u.id=p.user_id')
                ->field('p.id,p.phone,p.area_id,p.attachment,p.money,p.house_type,p.updatetime,p.click,p.fen_num,p.contract_type,p.type,p.name,p.user_id,p.lng,p.photos,p.lat,p.tags,p.address,p.desc,u.nickname,u.avatar,u.loginip')
                ->where($where)->find();
            if(!$item){
                $this->error('查询失败');
            }
            ThisModel::where(['id'=>$id])->setInc('fen_num',1);

            $this->success('分享成功');

        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 收藏/点赞
     */
    public function collect()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $user_id = $this->auth->id;
            $id = (int)$getData['id'];
            $keys = $this->get_keys('collect' . $user_id . '_' . $id);
            if (!$this->check_repeat($keys, 3)) {
                $this->error('您点击的太快了');
            }
            $data = [
                'user_id' => $user_id,
                'product_id' => $id,
            ];
            $text = '';
            if ($getData['type'] == 1) {
                $text = '收藏';
                $data['type'] = Collection::TYPE_CANG;
            } elseif ($getData['type'] == 2) {
                $text = '点赞';
                $data['type'] = Collection::TYPE_ZAN;
            }
            $info = ThisModel::where(['id' => $id, 'status' => ThisModel::STATUS_NORMAL])->find();
            if (empty($info)) {
                $this->error('已被删除');
            }
            $collect_info = Collection::where($data)->find();
            if (!$collect_info) {
                $data['operate_type'] = $getData['operate_type'];
                (new Collection())->insert($data);
            } else {
                if ($getData['operate_type'] != $collect_info['operate_type']) {
                    if ($collect_info['operate_type'] == Collection::STATUS_NORMAL) {
                        (new Collection())->where(['id' => $collect_info['id']])->update(['operate_type' => Collection::STATUS_DISABLE]);
                    } else {
                        (new Collection())->where(['id' => $collect_info['id']])->update([
                            'operate_type' => Collection::STATUS_NORMAL,
                            'create_time' => date('Y-m-d H:i:s')
                        ]);
                    }
                }
            }
            $this->success($text . '成功');
        }
    }

    public function collect_list()
    {
        $user_id = $this->auth->id;
        $limit = $this->request->param('limit/d', 10);
        $field = 'p.id,p.phone,p.attachment,p.updatetime,p.click,p.fen_num,p.area_id,p.money,p.house_type,p.contract_type,
        p.send_type,p.type,p.name,p.user_id,p.lng,p.photos,p.lat,p.tags,p.address,p.desc,p.floor,
        u.nickname,u.avatar,u.loginip';
        $list = Collection::alias('c')
            ->join('user_publish p', 'c.product_id = p.id')
            ->join('fa_user u', 'u.id=p.user_id')
            ->field($field)
            ->where([
                'c.user_id' => $user_id,
                'c.type' => Collection::TYPE_CANG,
                'c.operate_type' => Collection::STATUS_NORMAL,
            ])
            ->order('c.create_time', 'desc')
            ->paginate($limit)
            ->each(function ($item) use ($user_id) {
                $item['updatetime'] = date('Y-m-d H:i', $item['updatetime']);
                $item['first_photos_path'] = $item['photos_path'][0] ?? [];
                $item['photos_path'] = get_all_img_path($item['photos']);
                $item['attachment_path'] = get_all_img_path($item['attachment']);
                $house_type_text = '';
                if (!empty($item['house_type'])) {
                    $house_type_text = ThisModel::getHouseTypeList(1, $item['house_type']);
                }
                $contract_type_text = '';
                if (!empty($item['contract_type'])) {
                    $contract_type_text = ThisModel::getContractTypeList(1, $item['contract_type']);
                }
                $type_text = '';
                if (!empty($item['type'])) {
                    $type_text = ThisModel::getTranTypeList(1, $item['type']);
                }
                $item['send_type_text'] = ThisModel::getSendTypeList(1, $item['send_type']);
                $item['house_type'] = $house_type_text;
                $item['contract_type'] = $contract_type_text;
                $item['type_text'] = $type_text;
                $area = '';
                if (!empty($item['area_id'])) {
                    $area_info = ConfigValueModel::where(['option_id' => $item['area_id'], 'cid' => 2])->find();
                    $area = $area_info['option_name'] ?? '';
                }
                $item['area_info'] = $area;
            });

        $this->success('成功', $list);
    }


    public function add_comment()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'pub_id|帖子ID' => 'require',
            'content|内容' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        $row = ThisModel::find($params['pub_id']);
        if (empty($row)) $this->error('帖子不存在');


        $params['user_id'] = $this->auth->id;
        $params['pid'] = intval($params['pid'] ?? 0);
        $params['status'] = 1;
        $params['content'] = filter_words($params['content'] ?? '');
        $create = PublishComment::create($params, true);

        if ($create->id) {
            User::score(1, $this->auth->id, '回帖赠送', 4);
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    public function del_comment()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'comment_id|评论ID' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        $row = PublishComment::get($params['comment_id']);
        if (empty($row)) $this->error('数据不存在');
        if ($row['user_id'] != $this->auth->id) {
            $this->error('只能删除自己的');
        }

        if ($row->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }


    public function top_config()
    {
        $data = ThisModel::getTopConfig();
        $this->success('ok', $data);
    }


}
